//
//  gooleLogInBingPoneViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/10/25.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import SVProgressHUD
import Foundation
import TKSubmitTransition
import QuartzCore
import GoogleSignIn
import SwiftyUserDefaults

class gooleLogInBingPoneViewController: BaseViewController, UIViewControllerTransitioningDelegate {
    var timebutton: TimerButton!
    var btn: TKTransitionSubmitButton!
    var googleID :String!
    var phoneTextField :UITextField!
    var codeTextField :UITextField!
    var mypassWorldField :UITextField!
    var myYaoQingField :UITextField!
    
    var btnFromNib: TKTransitionSubmitButton!
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        makeBaseUI()
    }
    //MARK: - PrivateMethods
    func makeBaseUI(){
        let bg = UIImageView(image: UIImage(named: "Login"))
        bg.frame = self.view.frame
        self.view.addSubview(bg)
        let myImageView = UIImageView(image: UIImage(named: "THTC币@2x"))
        self.view.addSubview(myImageView)
        myImageView.snp.makeConstraints { (make) in
            make.top.equalTo(110)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 64, height: 64))
        }
        let backBtn = UIButton(type: .system)
        backBtn.setTitle(XALanguageManager.getString(key: "取消"), for: .normal)
        self.view.addSubview(backBtn)
        backBtn.setTitleColor(UIColor.white, for: .normal)
        backBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        backBtn.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(30)
            make.right.equalTo(self.view).offset(-15)
            make.size.equalTo(CGSize(width: 60, height: 44))
        }
        backBtn.addTarget(self, action: #selector(LogInViewController.backAction), for: .touchUpInside)
        
        
        
        phoneTextField = ZTYTextField(leftView: nil, frame: CGRect(x: 15 , y: 200, width: 90, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(phoneTextField)
        phoneTextField.textColor = UIColor.white
        //        phoneTextField.keyboardType = .numberPad
        
        let placeholserAttributes2 = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        phoneTextField.font = UIFont.systemFont(ofSize: 16)
        phoneTextField.keyboardType = .numberPad
        phoneTextField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key: "+86"),attributes: placeholserAttributes2)
        phoneTextField.textAlignment = .center
        phoneTextField.isUserInteractionEnabled = false
        //        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        phoneTextField.layer.borderColor = UIColor.white.cgColor
        
        
        
        
        
        
        phoneTextField = ZTYTextField(leftView: nil, frame: CGRect(x: 15 + 100 , y: 200, width: kScreenWidth - 130, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(phoneTextField)
        phoneTextField.textColor = UIColor.white
        //        phoneTextField.keyboardType = .numberPad
        let placeholserAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        phoneTextField.font = UIFont.systemFont(ofSize: 16)
        phoneTextField.keyboardType = .numberPad
        phoneTextField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key: "请输入手机号"),attributes: placeholserAttributes)
        //        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        phoneTextField.layer.borderColor = UIColor.white.cgColor
        
        codeTextField = ZTYTextField(leftView: nil, frame: CGRect(x: 15 , y: 200 + 53, width: kScreenWidth - 130, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(codeTextField)
        codeTextField.isSecureTextEntry = true
        codeTextField.textColor = UIColor.white
        
        let placeholserAttributes1 = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        codeTextField.font = UIFont.systemFont(ofSize: 16)
        codeTextField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key:"请输入验证码"),attributes: placeholserAttributes1)
        
        timebutton = TimerButton(frame: CGRect(x: kScreenWidth - 100 , y: 200 + 53, width: 90, height: 38))
        
        timebutton.layer.cornerRadius = 5
        
        mypassWorldField = ZTYTextField(leftView: nil, frame: CGRect(x: 15, y: 200 + 53 + 53, width: kScreenWidth - 30, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(mypassWorldField)
        mypassWorldField.textColor = UIColor.white
        //        phoneTextField.keyboardType = .numberPad
        
        let placeholserAttributes3 = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        mypassWorldField.font = UIFont.systemFont(ofSize: 16)
        mypassWorldField.keyboardType = .numberPad
        mypassWorldField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key: "请输入密码"),attributes: placeholserAttributes3)
        //InvitationCodeField.textAlignment = .center
        //        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        mypassWorldField.layer.borderColor = UIColor.white.cgColor
        
        
        myYaoQingField = ZTYTextField(leftView: nil, frame: CGRect(x: 15, y: 200 + 53 + 53 + 53, width: kScreenWidth - 30, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(myYaoQingField)
        myYaoQingField.textColor = UIColor.white
        //        phoneTextField.keyboardType = .numberPad
        let placeholserAttributes4 = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        myYaoQingField.font = UIFont.systemFont(ofSize: 16)
        myYaoQingField.keyboardType = .numberPad
        myYaoQingField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key: "请输入邀请码"),attributes: placeholserAttributes4)
        //InvitationCodeField.textAlignment = .center
        //        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        myYaoQingField.layer.borderColor = UIColor.white.cgColor
        
        
        
        //        timebutton.setTitle(XALanguageManager.getString(key: "发送"), for: .normal)
        //        timebutton.setTitle(XALanguageManager.getString(key: "发送"), for: .normal)
        timebutton.setup(XALanguageManager.getString(key: "发送"), timeTitlePrefix: "", aTimeLength: 60)
        timebutton.addBorder(side:.right, thickness: 0.5, color: UIColor.white)
        timebutton.addBorder(side:.left, thickness: 0.5, color: UIColor.white)
        timebutton.addBorder(side:.top, thickness: 0.5, color: UIColor.white)
        timebutton.addBorder(side:.bottom, thickness: 0.5, color: UIColor.white)
        self.view.addSubview(timebutton)
        timebutton.clickBtnEvent = {
            () -> Void in
            
            if !self.timebutton.isWorking{
                getData()
                //访问接口，获取验证码
            }
        }
        func getData() {
            //
            MyNetwork.request(target: .sendcode(mobile: phoneTextField.text!, token: String().md5(inString: "w2ZP4b~y1xv9A!ir38&Z"), type: "6"), success: { (result) in
                kLog(result)
                let needModel = BaseModel()
                needModel.yy_modelSet(with: result as! [AnyHashable : Any])
                
                if needModel.code == 1111{
                    self.timebutton.isWorking = true
                    self.view.makeToast(XALanguageManager.getString(key: XALanguageManager.getString(key: "成功")))
                }else{
                    self.timebutton.setup(XALanguageManager.getString(key: "发送"), timeTitlePrefix: "", aTimeLength: 60)
                    kLog(needModel.message)
                    self.view.makeToast(XALanguageManager.getString(key: XALanguageManager.getString(key: "失败")))
                }
                
            }) { (error) in
                self.timebutton.setup(XALanguageManager.getString(key: "发送"), timeTitlePrefix: "", aTimeLength: 60); self.view.makeToast(error.localizedDescription)
                //                kLog(error.localizedDescription)
            }
        }
        //        timebutton.addTarget(self, action: #selector(ZhuCeViewController.sendAction), for: .touchUpInside)
        
        
        //        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        codeTextField.layer.borderColor = UIColor.white.cgColor
        
        
        //        let zhuceBtn = UIButton(type: .system)
        //        zhuceBtn.setTitle(XALanguageManager.getString(key: "注册"), for: .normal)
        //        self.view.addSubview(zhuceBtn)
        //        zhuceBtn.setTitleColor(UIColor.white, for: .normal)
        //        zhuceBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        //        zhuceBtn.contentHorizontalAlignment = .left
        //        zhuceBtn.snp.makeConstraints { (make) in
        //            make.top.equalTo(codeTextField.snp.bottom).offset(20)
        //            make.left.equalTo(self.view).offset(15)
        //            make.size.equalTo(CGSize(width: 120, height: 15))
        //        }
        
        
        //        zhuceBtn.addTarget(self, action: #selector(LogInViewController.backAction), for: .touchUpInside)
        //
        //
        //        let passwordForgetBtn = UIButton(type: .system)
        //        passwordForgetBtn.contentHorizontalAlignment = .right
        //        passwordForgetBtn.setTitle(XALanguageManager.getString(key: "忘记密码"), for: .normal)
        //        self.view.addSubview(passwordForgetBtn)
        //        passwordForgetBtn.setTitleColor(UIColor.white, for: .normal)
        //        passwordForgetBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        //        passwordForgetBtn.snp.makeConstraints { (make) in
        //            make.top.equalTo(codeTextField.snp.bottom).offset(20)
        //            make.right.equalTo(self.view).offset(-15)
        //            make.size.equalTo(CGSize(width: 120, height: 15))
        //        }
        //        passwordForgetBtn.addTarget(self, action: #selector(LogInViewController.backAction), for: .touchUpInside)
        //
        
        
        btn = TKTransitionSubmitButton(frame: CGRect(x: 15, y: 420, width: kScreenWidth - 30, height: 44))
        btn.layer.cornerRadius = 4;
        btn.backgroundColor = UIColor("#297EFB")
        //        btn.frame.bottom = self.view.frame.height - 60
        
        btn.setTitle(XALanguageManager.getString(key: "完成"), for: UIControlState())
        btn.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 14)
        self.view.addSubview(btn)
        btnFromNib = TKTransitionSubmitButton()
        btn.addTarget(self, action: #selector(ZhuCeViewController.nextAction), for: UIControlEvents.touchUpInside)
    }
    
    @objc func backAction(){
        
        self.dismiss(animated: true) {
            
        }
    }
    @objc func  sendAction() {
        
    }
    @objc func nextAction()  {
        if phoneTextField.text?.count != 11 {
            SVProgressHUD.showError(withStatus: "请输入正确手机号码")
            return;
        }
        
        if (mypassWorldField.text?.count)! < 6 {
            SVProgressHUD.showError(withStatus: XALanguageManager.getString(key: "密码不能小于6位"))
            return;
        }
        
        
        
        MyNetwork.request(target: .checkcode(mobile: phoneTextField.text!, type: "6", code: codeTextField.text!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                self.onTapButton(self.btn);
            }else{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            self.navigationController?.view.makeToast(error.localizedDescription)
            kLog(error.localizedDescription)
        }
    }
    
    @objc func onTapButton(_ button: TKTransitionSubmitButton) {
        MyNetwork.request(target: .thirdlogin(google_id: self.googleID, mobile: phoneTextField.text!, password: String().md5(inString: mypassWorldField.text!), invite_user_mobile: myYaoQingField.text!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                let userModel = LogInModel()
                userModel.yy_modelSet(with: (result as AnyObject)["data"] as! [AnyHashable : Any]);
                Defaults[.isLogInKey] = true
                Defaults[.userID] = userModel.ids
                Defaults[.qrCodeUrl] = userModel.secret
                Defaults[.content] = userModel.account
                Defaults[.userPhone] = userModel.mobile;
                 Defaults[.nick_name] = userModel.nick_name;
               Defaults[.vip_code] = userModel.vip_code;
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "成功"))
                
//                self.view.bringSubview(toFront: self.btnFromNib)
                
                
                button.animate(0.7, CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), completion: { () -> () in
                    
                    self.dismiss(animated: false, completion: {
                        
                    })
                })
                
                self.view.bringSubview(toFront: self.btnFromNib)
            }else{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
        
        
    }
    
    // MARK: UIViewControllerTransitioningDelegate
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return TKFadeInAnimator(transitionDuration: 0.5, startingAlpha: 0.8)
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return nil
    }
}

